package web;


import pojo.User;
import pojo.UserInfo;
import service.UserInfoService;
import service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    private UserService userService = new UserService();

    private UserInfoService userInfoService = new UserInfoService();


    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //处理POST请求的乱码问题
        request.setCharacterEncoding("utf-8");

//        获取request参数
        String username  = request.getParameter("username");
        String password = request.getParameter("pwd");
        String type = request.getParameter("type");
        System.out.println(username);
        System.out.println(password);
        System.out.println(type);

//      查询用户是否存在
        User user = userService.selectOne(username, password);

//        设置返回数据格式
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        if (user !=null){
//            如果用户存在，判断登录方账号类型是否正确
            if (!type.equals(user.getType())){
                request.setAttribute("result","您账号类型不正确，请重新选择账号类型");
                request.getRequestDispatcher("/login.jsp").forward(request,response);
            }else {
//                如果账号密码和账号类型都正确，判断登录方的身份
                if (type.equals("0")){
//                    管理员，转发到AdminServlet
                   request.getRequestDispatcher("/AdminServlet").forward(request,response);

                }else {
//                    普通用户,查询该登录用户信息,转发到user.jsp进行展示
                    UserInfo userInfo = userInfoService.seletUserInfo(username);
                    request.setAttribute("userInfo",userInfo);
                    request.getRequestDispatcher("/user.jsp").forward(request,response);
                }
            }
        }else {
//            如果用户不存在，则账号密码至少由一个错误
            request.setAttribute("result","您输入的账号和密码错误，请重新输入");
            request.getRequestDispatcher("/login.jsp").forward(request,response);
        }




    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}